<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use Illuminate\Http\Request;
use App\Models\Authorization;
use App\Models\UserCoupon;
use App\Models\Shop;
use App\Models\ShopCoupon;
use App\Models\CouponCode;
use App\Jobs\SendRegisterEmail;
use Log;

class ShopController extends BaseController
{
    
    /**
     *
     * 获取商铺列表
     * @param {Object} Request
     */
    public function index(Request $request)
    {
        //$longitude = $request->headers['longitude'];
        $longitude = $request->get('longitude');
		$latitude  = $request->get('latitude');
		$page      = $request->get('page');
		$size      = $request->get('size');
		$keyword   = $request->get('keyword');
		$begin     = ($page - 1) * $size;
        $queryNum  = $begin + $size;
		
		$hosts    = array(env('ELASICSEARCHHOST'));
		$client   = ClientBuilder::create()->setHosts($hosts)->build();
		$must     = [
					'match' => [
						'name' => $keyword
					]
				];
		$query    = [
			'bool' => [
				'filter' => [
					"geo_distance" => [
						"distance" => "10000km",
						"location" => [
							"lat" => $latitude,
							"lon" => $longitude
						]
					]
				]
			]
		];
		if ($keyword) {
			$query['bool']['must'] = $must;
		}
		$sort = [
			"_geo_distance" => [
				"location" => [
					"lat" => $latitude,
					"lon" => $longitude
				],
				"order" => "asc",
				"unit" => "km"
			]
		];
		$params   = [
			'index' => 'cut_shop',
			'type'  => '_doc',
			'body'  => [
				'from'  => $begin,
				'size'  => $size,
				'query' => $query,
				'sort'  => $sort
			]
  		]; 
		//return $this->returnSuccess($params);
		$response = $client->search($params);
		$shop_ids = [];
		$shopHits = $response['hits']['hits'];
		//return $this->returnSuccess($shopHits);
		foreach ($shopHits as $item) {
			\array_push($shop_ids, $item['_id']);
		}
        $shops = Shop::whereIn('id', $shop_ids)->get();
        foreach ($shops as $k => $shop) {
			if ($k < $begin || $k >= ($begin + $size)) {
			    unset($shops[$k]);
				continue;
			}   
            $pics = $shop>pics;
            foreach ($pics as $key => $pic) {
                $new_pic = env('CUT_IMAGE_UTL') . $pic;
                $pics[$key] = $new_pic;
            }
            $shops[$k]['pics'] = $pics;
			foreach ($shopHits as $shop) {
				if ($shop['_id'] == $shop>id) {
					$shops[$k]['distance'] = \round($shop['sort'][0],4);
				}
			}
			if($shop>view_pic){
				$shops[$k]['view_pic'] = env('CUT_IMAGE_UTL') .$shop>view_pic;
			}
        }
        return $this->returnSuccess($shops);
    }
    
    /*
     * 获取商铺的详细信息
	 * 1、
     */
    public function detail(Request $request)
    {
        $id = $request->get('id');
		if ($request->user()) {
			$user_id = $request->user()->id;
		} else {
			$user_id = -1;
		}

        $shop = Shop::with('coupons')->with('products')->where('id', '=', $id)->first();
        $pics = is_array($shop->pics) ? $shop->pics : [];
        foreach ($pics as $key => $pic) {
            $new_pic = env('CUT_IMAGE_UTL') . $pic;
            $pics[$key] = $new_pic;
        }
		$shop->pics = $pics;
		//优惠券
        $coupons = $shop->coupons;
        foreach ($coupons as $coupon) {
            $coupon->is_fetched = 'N';
            $userCoupon = UserCoupon::where('user_id', '=', $user_id)
                        ->where('s_id', '=', $coupon->pivot->s_id)
                        ->where('c_id', '=', $coupon->pivot->c_id)
                        ->first();
            if ($userCoupon) {
                $coupon->is_fetched = 'Y';
            }
        }
		//商品列表
		$products = $shop->products;
		foreach($products as &$product){
			if($product->view_pic){
				$product->view_pic = env('CUT_IMAGE_UTL') .$shop->view_pic;
			}
			$pics = is_array($product->pics) ? $product->pics : [];
			foreach ($pics as $key => $pic) {
			    $new_pic = env('CUT_IMAGE_UTL') . $pic;
			    $pics[$key] = $new_pic;
			}
			$product->pics = $pics;
		}
        
        return $this->returnSuccess($shop);
    }
	
	/**
	 * 获取优惠券
	 * @param {Object} Request $request
	 */
	public function fetchCoupon(Request $request)
	{
		$user_id = $request->user()->id;
	    $s_id    = $request->get('s_id');
	    $c_id    = $request->get('c_id');
	    $userCoupon = UserCoupon::where('user_id', '=', $user_id)
	                    ->where('s_id', '=', $s_id)
	                    ->where('c_id', '=', $c_id)
	                    ->first();
	    if (empty($userCoupon)) {
			$sc = ShopCoupon::where("s_id", '=', $s_id)->where("c_id", "=", $c_id)->first();
			if (empty($pc)) {
				return $this->returnSuccess('Y');
			}
			$scc = CouponCode::where('sc_id', "=", $sc->id)->where('status', '=', 'N')->first();
			if (empty($scc)) {
				return $this->returnFail('领取失败，您来晚了，优惠券已经领完');
			}
			$scc->user_id = $user_id;
			$scc->save();
	        $userCoupon = new UserCoupon();
	        $userCoupon->user_id = $user_id;
	        $userCoupon->s_id    = $s_id;
	        $userCoupon->c_id    = $c_id;
	        $userCoupon->save();
	    } else {
	        return $this->returnSuccess('Y');
	    }
	    return $this->returnSuccess('Y');
	}
}
